from google.appengine.api import users
from google.appengine.api import memcache

class CacheMiddleware(object):
    """
    This is a very simple middleware that add cache functionality
    """
    def process_request(self, request):
        request._cache_update_cache = False

        #only use cache for anonymous user
        if users.get_current_user():
            return None
        
        if request.method != 'GET':
            return None
            
        key = self.generate_key(request) 
        try:
            response = memcache.get(key)
            if response is not None:
                return response
        except:
            pass
        
        request._cache_update_cache = True
        return None
          
    def process_response(self, request, response):
        if request.method == 'POST':
            memcache.flush_all()
        
        "Sets the cache, if needed."
        if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache:
            # We don't need to update the cache, just return.
            return response
        
        if request.method != 'GET':
            return response

        if not response.status_code == 200:
            return response
        
        key = self.generate_key(request) 
        try:
            memcache.set(key, response)
        except:
            pass        
        
        return response
        
    def generate_key(self, request):
        if request.host_url:
            return request.host_url + request.get_full_path()
        else:
            return request.get_full_path()          
        